<template>
  <div id="sysUser">
    <el-form
      :inline="true"
      :model="sysRoleQueryRequest"
      class="demo-form-inline"
    >
      <el-form-item label="用户名">
        <el-input
          v-model="sysRoleQueryRequest.username"
          placeholder="用户名"
          clearable
        />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="sysRoleQueryRequest.createTimeBegin"
          type="date"
          placeholder="Pick a date"
          clearable
        />
        -
        <el-date-picker
          v-model="sysRoleQueryRequest.createTimeEnd"
          type="date"
          placeholder="Pick a date"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchPage">查找</el-button>
      </el-form-item>
    </el-form>
    <div class="addUserButton" style="margin: 5px; padding: 5px;">
      <el-button type="success" round @click="addShow">+ 添加</el-button>
      <el-button type="primary" round @click="reset">重置</el-button>
      <el-button type="danger" round @click="batchDelete">批量删除</el-button>
    </div>
    <div>
      <el-table
        :data="tableData"
        style="width: 100%"
        @selection-change="selectChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column property="id" label="id" width="120" />
        <el-table-column property="roleName" label="用户名" />
        <el-table-column property="roleCode" label="用户编码" />
        <el-table-column property="createTime" label="创建时间">
          <template #default="scope">
            <el-date-picker
              v-model="scope.row.createTime"
              value-format="yyyy-MM-dd"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="warning" @click="showMenu(scope.row.id)">
              分配菜单
            </el-button>
            <el-button type="primary" @click="changeShow(scope.row)">
              修改
            </el-button>
            <el-button type="danger" @click="doDelete(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="page.pageNum"
          v-model:page-size="page.pageSize"
          :page-sizes="[2, 4, 6, 8]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
          @size-change="fetchPage"
          @current-change="fetchPage"
        />
      </div>
    </div>
    <!-- 添加角色表单对话框 -->
    <el-dialog v-model="dialogVisible" title="添加或修改" width="30%">
      <el-form label-width="120px">
        <el-form-item label="角色名称">
          <el-input v-model="sysRole.roleName" />
        </el-form-item>
        <el-form-item label="角色Code">
          <el-input v-model="sysRole.roleCode" />
        </el-form-item>
        <el-form-item>
          <div v-if="sysRole.id">
            <el-button type="primary" @click="changeRole">
              提交
            </el-button>
          </div>
          <div v-else>
            <el-button type="primary" @click="addRole">提交</el-button>
          </div>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--分配菜单界面-->
    <el-dialog v-model="dialogVisibleMenu" title="分配菜单" width="30%">
      <el-tree
        ref="treeRef"
        style="max-width: 600px"
        :data="sysMenuTreeList"
        show-checkbox
        default-expand-all
        node-key="id"
        highlight-current
        :props="defaultProps"
      />
      <el-form-item>
        <el-button type="primary" @click="updateRoleMenu">
          提交
        </el-button>
        <el-button @click="dialogVisibleMenu = false">取消</el-button>
      </el-form-item>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, onMounted, ref, nextTick } from 'vue'
import { ElMessage, ElMessageBox, ElTable } from 'element-plus'
import { ElTree } from 'element-plus'
import {
  getRoleList,
  doAddRole,
  doFindRoleById,
  doChangeRole,
  deleteSysRoleById,
  doBatchDelete,
  findMenuTree,
  findMenuByRoleId,
  doUpdateRoleMenu,
} from '@/api/sysRole.js'

onMounted(async () => {
  await fetchPage()
})
const sysRoleQueryRequest = reactive({
  username: '',
  createTimeBegin: '',
  createTimeEnd: '',
})
const page = reactive({
  pageSize: 4,
  pageNum: 1,
  total: '',
})
const sysRole = reactive({
  id: '',
  roleName: '',
  roleCode: '',
})
const tableData = ref([])
const dialogVisible = ref(false)
let selectSysRoles = []

// 分页查询
const fetchPage = async () => {
  const ref = await getRoleList(
    page.pageNum,
    page.pageSize,
    sysRoleQueryRequest
  )
  if (ref.code === 200) {
    tableData.value = ref.data.records
    page.total = ref.data.total
  }
}
// 重置
const reset = () => {
  page.pageNum = 1
  page.pageSize = 4
  sysRoleQueryRequest.createTimeBegin = ''
  sysRoleQueryRequest.createTimeEnd = ''
  sysRoleQueryRequest.username = ''
  sysRole.id = ''
  sysRole.roleCode = ''
  sysRole.roleName = ''
  fetchPage()
}
//进入添加
const addShow = () => {
  sysRole.roleCode = ''
  sysRole.roleName = ''
  sysRole.id = ''
  dialogVisible.value = true
}
// 添加用户
const addRole = async () => {
  const ref = await doAddRole(sysRole)
  if (ref.code === 200) {
    ElMessage.success('成功')
  } else {
    ElMessage.error(ref.message)
  }
  dialogVisible.value = false
  fetchPage()
}
// 查询角色
const findRole = async id => {
  const ref = await doFindRoleById(id)
  if (ref.code === 200) {
    sysRole.roleCode = ref.data.roleCode
    sysRole.roleName = ref.data.roleName
  } else {
    ElMessage.error(ref.message)
  }
}
//进入修改
const changeShow = row => {
  sysRole.roleCode = row.roleCode
  sysRole.id = row.id
  sysRole.roleName = row.roleName
  dialogVisible.value = true
}
// 修改用户
const changeRole = async () => {
  const ref = await doChangeRole(sysRole)
  if (ref.code === 200) {
    ElMessage.success('成功')
  } else {
    ElMessage.error(ref.message)
  }

  dialogVisible.value = false
  fetchPage()
}
// 删除用户
const doDelete = async id => {
  ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const { code } = await deleteSysRoleById(id)
      if (code === 200) {
        ElMessage.success('删除成功')
        fetchPage()
      }
    })
    .catch(() => {
      ElMessage.info('取消删除')
    })
}

// 批量删除
const selectChange = selection => {
  console.log(selection)
  selectSysRoles = selection
}
const batchDelete = async => {
  if (selectSysRoles.length === 0) {
    ElMessage('请选择删除对象')
    return
  }
  ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      var idList = []
      selectSysRoles.forEach(element => {
        idList.push(element.id)
      })
      const ref = await doBatchDelete(idList)
      if (ref.code === 200) {
        ElMessage.success('删除成功')
        fetchPage()
      }
    })
    .catch(() => {
      ElMessage.info('取消删除')
    })
}

// 分配菜单

const dialogVisibleMenu = ref(false)
const defaultProps = {
  children: 'children',
  label: 'title',
}
// 存储所有菜单
// eslint-disable-next-line no-undef
const treeRef = ref<InstanceType<typeof ElTree>>()
const sysMenuTreeList = ref([])
// 存储勾选的菜单
const checkedDataId = ref([])

// 分配菜单 1、显示菜单界面，展示所有菜单，查找已分配的菜单
const showMenu = async id => {
  checkedDataId.value = []
  sysMenuTreeList.value = []
  sysRole.id = id
  // 查询所有菜单
  const ref = await findMenuTree()
  sysMenuTreeList.value = ref.data
  // 查询拥有菜单
  const { data } = await findMenuByRoleId(id)
  await data.forEach(element => {
    checkedDataId.value.push(element.id)
  })
  dialogVisibleMenu.value = true
  await nextTick()
  treeRef.value.setCheckedKeys(checkedDataId.value, false)
}
const updateRoleMenu = async () => {
  // await nextTick()
  // 得到了选择的menu id
  checkedDataId.value = treeRef.value.getCheckedKeys(false)
  const res = await doUpdateRoleMenu(sysRole.id, checkedDataId.value)
  if (res.code === 200) {
    ElMessage.success('修改成功')
  } else ElMessage.error(res.message)
  dialogVisibleMenu.value = false
}
</script>
<style scoped>
#sysUser .pagination-container {
  display: flex;
  justify-content: center; /* 水平居中 */
  margin: 20px 0; /* 可选：添加上下间距 */
}
</style>
